package com.dingdang.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dingdang.entity.OrderDetails;
import com.dingdang.entity.TbGiftGoods;
import com.dingdang.entity.TbGiftLog;
import com.dingdang.mapper.OrderDetailsMapper;
import com.dingdang.mapper.TbGiftGoodsMapper;
import com.dingdang.mapper.TbGiftLogMapper;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup = "trs-group",topic = "gift-topic")
public class ReserveListenerController implements RocketMQListener<Long>, RocketMQPushConsumerLifecycleListener
{
    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private TbGiftGoodsMapper giftGoodsMapper;

    @Autowired
    private TbGiftLogMapper giftLogMapper;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Override
    public void onMessage(Long obj)
    {
        System.out.println(obj);
    }

    @Override
    //开启ack机制
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer)
    {

        //普通消息
        defaultMQPushConsumer.registerMessageListener(
            new MessageListenerConcurrently()
              {
                  @Override
                  public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext)
                  {
                      //获取传来的信息
                      MessageExt messageExt =list.get(0);
                      int reconsumeTimes = messageExt.getReconsumeTimes();
                      System.err.println("消息的重试次数：" + messageExt.getReconsumeTimes());
                      try
                      {
                          Message message = list.get(0);
                          String s = new String(messageExt.getBody(),"utf-8");
                          System.out.println("message = " + s);
                          Long out_trade_no = Long.valueOf(s);
                          System.out.println("out_trade_no = " + out_trade_no);
                          //获取订单详情
                          //OrderDetails orderDetails = orderDetailsMapper.selectById(out_trade_no);
                          LambdaQueryWrapper<OrderDetails> wrapper = new LambdaQueryWrapper<>();
                          wrapper.eq(OrderDetails::getOrderId,out_trade_no);
                          List<OrderDetails> orderDetails = orderDetailsMapper.selectList(wrapper);
                          if((orderDetails.get(0).getStatus()).equals("2"))
                          {
                              TbGiftLog giftLog = new TbGiftLog();
                              giftLog.setUserId(orderDetails.get(0).getUid());
                              //生成从a到b的随机整数，即返回值[a，b]
                              int num=1+(int)(Math.random()*(7-1+1));

                              //设置小礼品记录
                              giftLog.setGiftGoodsId(Long.valueOf(num));
                              //Long uid = orderDetails.get(0).getUid();
                              //System.out.println("uid = " + uid);
                              //TbGiftGoods giftGoods = giftGoodsMapper.selectGoods(uid);
                              LambdaQueryWrapper<TbGiftGoods> wrapper2 = new LambdaQueryWrapper<>();
                              wrapper2.eq(TbGiftGoods::getGiftId,num);
                              List<TbGiftGoods> giftGoods = giftGoodsMapper.selectList(wrapper2);
                              if ((giftGoods.get(0).getGiftGoodsStock())>0)
                              {
                                  //小礼品库存减一
                                  LambdaUpdateWrapper<TbGiftGoods> wrapper1 = new LambdaUpdateWrapper();
                                  wrapper1.set(TbGiftGoods::getGiftGoodsStock,giftGoods.get(0).getGiftGoodsStock() -1);
                                  giftGoodsMapper.update(null,wrapper1);

                                  //记录向用户发放小礼品的信息
                                  giftLogMapper.insert(giftLog);
                              }
                              else
                              {
                                  System.out.println("礼品已经送完");
                              }
                          }
                          return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                      }
                      catch (Exception e)
                      {
                          //默认16次，设置重试次数和死信队列
                          if (reconsumeTimes >2)
                          {
                              System.err.println("以重试三次，放入自定义死信队列中");
                              //要提示borker消费成功了
                              return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                          }
                          e.printStackTrace();
                          return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                      }
                  }
              }

        );
    }


}
